package ru.dc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ru.dc.gui.swing.MainFrame;
import ru.dc.object.CommandListener;
import ru.dc.object.commands.Command;
import ru.dc.object.commands.CommandFactory;

import java.io.IOException;
import java.net.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: deady
 * Date: 29.10.2010
 * Time: 22:47:21
 */
public class ExternalListener extends Thread {

    private int port;
    private boolean stopped = false;
    private Log logger = LogFactory.getLog(getClass());
    private List<CommandListener> commandListeners = new ArrayList<CommandListener>();

    public void run() {
        logger.info("Started listening udp connections on port "+port);
        try {
            DatagramSocket socket = new DatagramSocket(port);
            while (!stopped) {
                logger.debug("Waiting incoming connection");
                byte[] buffer = new byte[1000];
                DatagramPacket request = new DatagramPacket(buffer, buffer.length);
                socket.receive(request);
                logger.debug("Accepted connection from "+request.getAddress());
                String s = new String(request.getData(), request.getOffset(), request.getLength(),  "Cp1251");
                if (s.endsWith("|")) {
                    s = s.substring(0, s.length()-1);
                }
                logger.trace("Recieved data: "+s);
                Command command = CommandFactory.getInstance().createCommand(s);
                fireCommandExtracted(command);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public boolean isStopped() {
        return stopped;
    }

    public void setStopped(boolean stopped) {
        this.stopped = stopped;
    }

    public void addCommandListener(CommandListener commandListener) {
        commandListeners.add(commandListener);
    }

    public void removeCommandListener(CommandListener commandListener) {
        commandListeners.remove(commandListener);
    }

    public void fireCommandExtracted(Command command) {
        logger.debug("Recieved command: "+command);
        CommandDispatchingThread.getInstance().addCommand(command);
/*
        for (CommandListener commandListener : commandListeners) {
            commandListener.commandRecieved(command);
        }
*/
    }

}
